package cn.addr.user.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import java.util.Iterator;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import cn.addr.server.message.XMLMessageUtil;
import cn.addr.user.dao.LinkPersonDao;
import cn.addr.user.dao.TagDao;
import cn.addr.user.model.LinkPerson;
import cn.addr.user.model.Tag;
import cn.addr.user.model.UserBean;

@SuppressWarnings("rawtypes")
public class LinkPersonCRUD {
	
	private LinkPersonDao personDao = LinkPersonDao.getInstance();
	private TagDao tagDao = TagDao.getInstance();

	
	@Test
	public void updateDatabase(){
		InputStream is;
		try {
			is = new FileInputStream(new File("constant.xml"));
			XMLMessageUtil.readRemoteXML(is, "kong");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	
	public void deleteAllUser(UserBean bean){
		DetachedCriteria dc1 = DetachedCriteria.forClass(LinkPerson.class);
		dc1.add(Restrictions.eq("user.id", bean.getId()));
		try {
			personDao.begin();
			List result = tagDao.search(dc1);
			for(Iterator it = result.iterator() ; it.hasNext() ;){
				LinkPerson o = (LinkPerson) it.next();
				personDao.delete(o);
				personDao.flush();
			}
			personDao.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			personDao.close();
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(Tag.class);
		dc.add(Restrictions.eq("user.id", bean.getId()));
		try {
			tagDao.begin();
			List result = tagDao.search(dc);
			for(Iterator it = result.iterator() ; it.hasNext() ;){
				Tag o = (Tag) it.next();
			
				tagDao.delete(o);
				tagDao.flush();
			}
			tagDao.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			tagDao.close();
		}
	}
	
	@Test
	public void database(){
		UserBean uu = new UserBean("kong","123");
		uu.setId(1L);
		deleteAllUser(uu);
	}
}
